Page({
  data: {
    dormId: null,
    dormInfo: null,
    showcaseImages: [],
    isLoading: true,
    error: '',
    userInfo: null
  },

  onLoad(options) {
    // 获取当前用户信息
    const userInfo = wx.getStorageSync('userInfo');
    this.setData({
      userInfo: userInfo
    });
    
    console.log('宿舍详情页 - 当前用户角色:', userInfo ? userInfo.role : '未登录');
    
    if (options.id) {
      this.setData({
        dormId: options.id
      });
      this.fetchDormDetails(options.id);
    } else {
      this.setData({
        isLoading: false,
        error: '未指定宿舍ID'
      });
      wx.showToast({
        title: '参数错误',
        icon: 'error'
      });
    }
  },

  fetchDormDetails(dormId) {
    this.setData({ isLoading: true, error: '' });
    
    console.log('正在获取宿舍详情，ID:', dormId);
    
    wx.cloud.callFunction({
      name: 'manageDorms',
      data: {
        action: 'get', // 使用 manageDorms 的 get action
        data: { 
          dormId: dormId
        }
      },
      success: res => {
        console.log('获取宿舍详情响应:', res);
        
        if (res.result && res.result.success && res.result.dorm) {
          this.setData({
            dormInfo: res.result.dorm,
            showcaseImages: res.result.dorm.showcaseImages || [],
            isLoading: false
          });
        } else {
          const errorMsg = (res.result && res.result.message) || '获取宿舍详情失败';
          console.error('获取宿舍详情失败:', errorMsg);
          
          this.setData({
            isLoading: false,
            error: errorMsg
          });
          wx.showToast({
            title: errorMsg,
            icon: 'none'
          });
        }
      },
      fail: err => {
        console.error('调用宿舍详情云函数失败:', err);
        
        this.setData({
          isLoading: false,
          error: '调用云函数失败: ' + (err.errMsg || JSON.stringify(err))
        });
        wx.showToast({
          title: '网络错误',
          icon: 'none'
        });
      }
    });
  },

  // 图片预览
  previewImage: function(e) {
    const current = e.currentTarget.dataset.src;
    const type = e.currentTarget.dataset.type;
    let urlsToPreview = [];

    if (type === 'showcase') {
      urlsToPreview = this.data.showcaseImages && this.data.showcaseImages.length > 0 ? this.data.showcaseImages : [current];
    } else {
      urlsToPreview = this.data.dormInfo && this.data.dormInfo.images && this.data.dormInfo.images.length > 0 ? this.data.dormInfo.images : [current];
    }

    wx.previewImage({
      current: current, // 当前显示图片的http链接
      urls: urlsToPreview // 需要预览的图片http链接列表
    });
  },

  onPullDownRefresh() {
    if (this.data.dormId) {
      this.fetchDormDetails(this.data.dormId).finally(() => {
        wx.stopPullDownRefresh();
      });
    }
  }
}); 